package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import jdk.nashorn.internal.runtime.regexp.joni.constants.OPSize;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gakki
 * @create 2022/5/3 16:21
 */
@Slf4j
@RestController
@RequestMapping("setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    /**
     * 套餐及菜品信息存储
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    public Result<String> saveWithSetmealDish(@RequestBody SetmealDto setmealDto) {
        log.info("套餐及菜品信息存储setmealDto：{}", setmealDto);
        setmealService.saveWithSetmealDish(setmealDto);
        return Result.success("套餐及菜品信息存储成功！");
    }

    /**
     * 套餐管理分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> queryByPage(Integer page, Integer pageSize, String name) {

        log.info("套餐管理分页查询page：{},pageSize:{},name:{}", page, pageSize, name);

        Page<Setmeal> setmealPage = new Page(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //根据name查询出setmeal
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.apply(name != null, "name REGEXP {0}", name).orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, lambdaQueryWrapper);

        //page数据拷贝，排除records，作为后续将categoryId替换为categoryName
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        //获取page中的record
        List<Setmeal> records = setmealPage.getRecords();

        //遍历records集合，将categoryId替换为categoryName
        List<SetmealDto> setmealDtoList = records.stream().map((item) -> {
            //创建setmealDao对象，并将setmeal进行拷贝
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            //获取category对象
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                //根据获取的category对象，获取对应的categoryName
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());

        //设置setmealDtoPage的records数据
        setmealDtoPage.setRecords(setmealDtoList);

        return Result.success(setmealDtoPage);
    }

    /**
     * 菜品管理删除或批量删除
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "setMealListCache",allEntries = true)
    @DeleteMapping
    public Result<String> deleteSetmeal(@RequestParam("ids") List<Long> ids) {
        log.info("菜品管理删除或批量删除ids：{}", ids);

        //直接删除setmeal中的数据
        setmealService.removeByIds(ids);

        //遍历ids集合，根据setmealId在setmealDish表中删除对应数据
        ids.forEach((id) -> {
            LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
            setmealDishService.remove(lambdaQueryWrapper);
        });
        return Result.success("菜品管理删除或批量删除成功！");
    }

    /**
     * 更改套餐启用状态
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setMealListCache",allEntries = true)
    @PostMapping("/status/{status}")
    public Result<String> enableOrDisableStatus(@PathVariable Integer status, @RequestParam("ids") List<Long> ids) {
        log.info("更改套餐启用状态，status:{},ids:{}", status, ids);
        //遍历ids集合，设置对应套餐的启用状态
        ids.forEach((id) -> {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", id);
            updateWrapper.set("status", status);
            setmealService.update(updateWrapper);
        });

        return Result.success("套餐启用状态更改成功！");
    }

    /**
     * 根据id查询setmeal，作为修改回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<SetmealDto> querySetmealById(@PathVariable Long id) {
        log.info("根据id查询setmeal，作为修改回显！id：{}", id);
        SetmealDto setmealDto = setmealService.querySetmealById(id);
        return Result.success(setmealDto);
    }

    /**
     * 套餐数据更新
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setMealListCache",allEntries = true)
    @PutMapping
    public Result<String> updateSetmeal(@RequestBody SetmealDto setmealDto) {
        log.info("套餐数据更新,setmealDto:{}", setmealDto);
        setmealService.updateSetmeal(setmealDto);
        return Result.success("套餐数据更新成功！");
    }

    /**
     * 套餐查询
     *
     * @param categoryId
     * @param status
     * @return
     */
    @Cacheable(value = "setMealListCache", key = "#categoryId+'_'+#status", unless = "#result == null")
    @GetMapping("/list")
    public Result<List<Setmeal>> setmealList(Long categoryId, Integer status) {
        log.info("套餐查询categoryId：{},status:{}", categoryId, status);
        //根据categoryId和status查询套餐
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId != null, Setmeal::getCategoryId, categoryId);
        lambdaQueryWrapper.eq(status != null, Setmeal::getStatus, status);
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = setmealService.list(lambdaQueryWrapper);
        //如果加载的数据为null，则直接返回
        return Result.success(setmealList);
    }

    /**
     * 套餐详情查询
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public Result<List<SetmealDish>> dishList(@PathVariable Long id) {
        log.info("套餐详情id:{}", id);

        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(lambdaQueryWrapper);

        //遍历setmealDishList，设置对应的图片名称
        setmealDishList = setmealDishList.stream().map((item) -> {
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(Dish::getId, item.getDishId());
            Dish dish = dishService.getOne(dishLambdaQueryWrapper);
            item.setImage(dish.getImage());
            return item;
        }).collect(Collectors.toList());

        return Result.success(setmealDishList);
    }


}
